#include "markdownhighlighter.h"
#include <QColor>
MarkdownHighlighter::MarkdownHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) {
    QColor lightBlue(173, 216, 230);
    QColor highGrey("#404040");
    QColor lightGreen("#606040");
    QColor deepBlue("#6060F0");

    // -------------------------------------------
    // set title
    QTextCharFormat titleFormat;
    titleFormat.setForeground(lightBlue);
    titleFormat.setFontWeight(QFont::Bold);
    // set title rule
    QRegularExpression titleRegex("^(#{1,6})\\s+(.*)$");
    highlightingRules.append({titleRegex, titleFormat});

    // --------------------------------------------
    // set code block
    QTextCharFormat codeFormat;
    //scodeFormat.setBackground(highGrey);
    codeFormat.setForeground(highGrey);
    // set code block rules
    QRegularExpression codeRegex("^```");
    highlightingRules.append({codeRegex, codeFormat});
    // --------------------------------------------
    // 设置表格高亮
    QTextCharFormat chartFormat;
    chartFormat.setForeground(lightGreen);
    chartFormat.setFontWeight(QFont::Bold);
    // set title rule
    QRegularExpression chartRegex("^\\s*\\|.*\\|\\s*$");
    highlightingRules.append({chartRegex, chartFormat});
    // --------------------------------------------
    // 设置链接高亮
    QTextCharFormat linkFormat;
    linkFormat.setForeground(deepBlue);
    // set title rule
    QRegularExpression linkRegex(R"(\[([^\]]+)\]\(([^)]+)\))");
    highlightingRules.append({linkRegex, linkFormat});
}

void MarkdownHighlighter::highlightBlock(const QString &text)
{
    // run all rulse
    for (const HighlightingRule &rule : qAsConst(highlightingRules)) {
        QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
        while (matchIterator.hasNext()) {
            QRegularExpressionMatch match = matchIterator.next();
            setFormat(match.capturedStart(), match.capturedLength(), rule.format);
        }
    }
}
